package com.game.sdk.handle;

import com.coment.dto.ApiNotify;
import com.coment.enums.PushType;
import com.coment.message.EquipmentInformationMessage;
import com.coment.message.RolesActionType;
import com.coment.message.roles.RolesActionMessage;
import com.coment.message.roles.StrengthAction;
import com.coment.message.user.UserInfoUpdatePush;
import com.coment.po.UserInfo;
import com.coment.po.UserPlayInfo;
import com.coment.po.roles.Roles;
import com.game.dao.user.UserPlayInfoDao;
import com.game.dao.user.roles.RolesDao;
import com.game.framework.ActorManager;
import com.game.logic.fighting.actor.RolesActor;
import com.game.logic.fighting.pve.GameServiceImpl;
import com.game.logic.roles.RolesService;
import com.game.sdk.ApiNotifyEvent;
import com.xs.action.exection.ActionException;
import com.xs.build.server.websocket.channel.ClientManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;


/// 3
@Slf4j
@Service
public class BarrageOperationChain {
    @Resource
    private RolesService rolesService;
    @Resource
    private GameServiceImpl gameServiceImpl;
    @Resource
    private RolesDao rolesDao;
    @Resource
    private UserPlayInfoDao userPlayInfoDao;


    @Async
    @EventListener(classes = ApiNotifyEvent.class)
    public void handle(ApiNotifyEvent event) {
        ApiNotify body = event.getBody();
        UserInfo userInfo = body.getUserInfo();
        Integer userInfoId = userInfo.getId();
        Integer anchorInfoId = body.getAnchorInfoId();

        try {
            this.beSeated(body, userInfoId, anchorInfoId);
            this.candidate(body, userInfoId, anchorInfoId);
            this.selectEquip(body, userInfoId, anchorInfoId);
        } catch (Exception e) {
            if (e instanceof ActionException) {
                log.error("ActionException", e);
                ClientManager.sendMessageToClient(anchorInfoId, e);
            } else {
                log.error("BarrageOperationChain error ", e);
            }
        }
    }

    /// 获取装备信息
    private void selectEquip(ApiNotify body, Integer userInfoId, Integer bestNewAnchorInfoId) {
        String seatRolesId = userPlayInfoDao.findByUserInfoIdOrCreate(userInfoId).getRecentlyPlayedRolesId();
        if (body.getPushType().equals(PushType.content.getValue()) && body.getContent().equals("查")) {
            EquipmentInformationMessage equipmentInformationMessage = this.rolesService.selectEquip(seatRolesId);
            ClientManager.sendMessageToClient(bestNewAnchorInfoId, equipmentInformationMessage);
        }

    }

    /// 选角色
    private void candidate(ApiNotify body, Integer userInfoId, Integer bestNewAnchorInfoId) {
        if (!body.getPushType().equals(PushType.content.getValue()) | body.getContent() == null) {
            return;
        }
        String content = body.getContent();
        if (content.length() < 2) {
            return;
        }
        if (!content.contains("选")) {
            return;
        }

        String roleName = content
                .replaceAll("选", "")
                .replaceAll("[^\\u4e00-\\u9fa5]", ""); // 只保留中文字符
        Integer cardId = RolesService.nameAndCardId.get(roleName);

        Roles roles = rolesDao.searchByUserInfoIdAndCardId(userInfoId, cardId);

        if (roles == null) {
            log.error("用户:{},无此角色", userInfoId);
            return;
        }

        String rolesId = roles.getId();
        RolesActionMessage rolesActionMessage = this.gameServiceImpl.beSeated(
                userInfoId,
                bestNewAnchorInfoId,
                rolesId
        );
        rolesActionMessage.setType(RolesActionType.SELECT_SUCCESS.getValue());
        rolesActionMessage.strength = ActorManager.ask(RolesActor.class, new StrengthAction(), rolesId);

        rolesActionMessage.setType(RolesActionType.SELECT_SUCCESS.getValue());
        ClientManager.sendMessageToClient(bestNewAnchorInfoId, rolesActionMessage);
    }

    /// 入座
    private void beSeated(
            ApiNotify body, Integer userInfoId, Integer bestNewAnchorInfoId
    ) {
        PushType type = PushType.fromValue(body.getPushType());
        switch (type) {
            case PushType.content -> {
                if (body.getContent().equals("1")) {
                    toSeated(userInfoId, bestNewAnchorInfoId);
                }
            }
            case PushType.gift -> {
                toSeated(userInfoId, bestNewAnchorInfoId);
            }
            default -> {}
        }
    }

    private void toSeated(Integer userInfoId, Integer bestNewAnchorInfoId) {
        UserPlayInfo userPlayInfo = userPlayInfoDao.findByUserInfoIdOrCreate(userInfoId);

        ClientManager.sendMessageToClient(bestNewAnchorInfoId, new UserInfoUpdatePush(
                userInfoId,
                userPlayInfo.getRecentlyPlayedAnchorInfoId(),
                userPlayInfo.getRecentlyPlayedRolesId(),
                userPlayInfo.getRecentlyPlayedPetId(),
                userPlayInfo.getRecentlyPlayedTitleId()
        ));

        String userRolesId = userPlayInfo.getRecentlyPlayedRolesId();

        if (userRolesId == null) {
            List<Roles> roles = rolesDao.searchAllByUserInfoId(userInfoId);
            if (roles.isEmpty()) {
                log.debug("用户:{},无角色", userInfoId);
            }
            userRolesId = roles.stream().findFirst().orElseThrow().getId();
        }
        RolesActionMessage rolesActionMessage = this.gameServiceImpl.beSeated(
                userInfoId, bestNewAnchorInfoId, userRolesId
        );
        rolesActionMessage.setType(RolesActionType.SEAT.getValue());
        rolesActionMessage.strength =
                ActorManager.ask(RolesActor.class, new StrengthAction(), userRolesId);
        ClientManager.sendMessageToClient(bestNewAnchorInfoId, rolesActionMessage);
    }
}
